package cn.bvin.lib.app;

import android.text.TextUtils;
import cn.bvin.lib.debug.SimpleLogger;
import cn.bvin.lib.module.net.RequestListener;
import cn.bvin.lib.module.net.RequestOperate;
import cn.bvin.lib.module.net.volley.RequestManager;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

public class RequestFragment<T> extends NetFragment implements RequestOperate<T>, RequestListener<T>, Response.ErrorListener, Listener<T>{

    private boolean isCurrentRequest;
    private Request<T> request;// 当前请求，保持唯一
    
    @SuppressWarnings("unchecked")
    @Override
    public void addRequest(Request<T> request) {
        if (getActivity() instanceof RequestActivity) {
            this.request = request;
            ((RequestActivity<T>)getActivity()).addRequest(request);
        } else {
            if (request==null) {
                SimpleLogger.log_w("addRequest", "resquest为Null");
                return;
            }
            if (TextUtils.isEmpty(request.getUrl())) {
                SimpleLogger.log_w("addRequest", "不存在URL的请求");
            } else {
                this.request = request;
                onRequestStart(request);
                SimpleLogger.log_i("addRequest", request.getUrl());
                RequestManager.addRequest(request);
            }
        }
        
    }

    @SuppressWarnings("unchecked")
    @Override
    public void cancelRequest() {
        if (getActivity() instanceof RequestActivity) {
            ((RequestActivity<T>)getActivity()).cancelRequest();
        } else {
            if (request != null)
                request.cancel();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void reloadRequest() {
        if (getActivity() instanceof RequestActivity) {
            ((RequestActivity<T>)getActivity()).reloadRequest();
        } else {
            addRequest(request);
        }
    }

    
    @Override
    public void onResponse(T arg0) {
        onRequestSuccess(arg0);
    }

    @Override
    public void onErrorResponse(VolleyError arg0) {
        onRequestFailure(arg0);
    }

    @Override
    public void onRequestStart(Request<T> resquest) {
        //TODO RequestActivity已经处理了一些事情，如果不在RequestActivity那就需要自己处理了
    }

    @Override
    public void onRequestSuccess(T result) {
        //TODO RequestActivity已经处理了一些事情，如果不在RequestActivity那就需要自己处理了
    }

    @Override
    public void onRequestFailure(VolleyError error) {
        //TODO RequestActivity已经处理了一些事情，如果不在RequestActivity那就需要自己处理了
    }


    public boolean isCurrentRequest()
    {
        return isCurrentRequest;
    }

    public void setCurrentRequest(boolean isCurrentRequest)
    {
        this.isCurrentRequest = isCurrentRequest;
    }
}
